package com.zdy.im.user.service.impl;


import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.ResultEnum;
import com.sixeco.framework.core.db.IterableConverter;
import com.sixeco.framework.core.db.ext.Query;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.util.PageUtils;
import com.sixeco.framework.util.excel.ExcelUtils;
import com.zdy.im.user.service.UserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;


import com.zdy.im.user.entity.UserInfo;
import com.zdy.im.user.dao.UserInfoDao;
import com.zdy.im.user.dto.request.UserInfoRequestDto;
import com.zdy.im.user.dto.response.UserInfoResponseDto;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;


/**
 * @ClassName: UserInfoDao.java
 * @Description: 用户表的数据交互处理类
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0.0
 * <p>
 * ----------------------------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 * ----------------------------------------------------------------------------
 * </p>
 */
@Service
public class UserInfoServiceImpl  implements UserInfoService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserInfoDao  userInfoDao;



    /**
     * 保存用户表同时更新数据库和缓存的实现方法
     * @param userInfoRequestDto UserInfoResponseDto
     * @return
     */
    public UserInfoResponseDto saveUserInfo(UserInfoRequestDto userInfoRequestDto){
        if(userInfoRequestDto== null){
            return null;
        }
        UserInfo userInfo = UserInfo.build().clone(userInfoRequestDto);
        boolean result = userInfoDao.save(userInfo);
        if(!result){
            return null;
        }
        UserInfoResponseDto userInfoResponseDto = UserInfoResponseDto.build().clone(userInfo);
        return userInfoResponseDto;


    }

    public boolean saveBatchUserInfo(Collection<UserInfoRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() !=  batchSize){
            return false;
        }
        List<UserInfo> list = new ArrayList<>();
        entityList.forEach(e -> list.add(UserInfo.build().clone(e)));
        boolean result = userInfoDao.saveBatch(list,batchSize);
        return result;
    }


    public boolean saveOrUpdateBatchUserInfo(Collection<UserInfoRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<UserInfo> list = new ArrayList<>();
        entityList.forEach(e -> list.add(UserInfo.build().clone(e)));
        boolean result = userInfoDao.saveOrUpdateBatch(list,batchSize);
        return result;
    }


    public boolean updateBatchById(Collection<UserInfoRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<UserInfo> list = new ArrayList<>();
        entityList.forEach(e -> list.add(UserInfo.build().clone(e)));
        boolean result =  userInfoDao.updateBatchById(list,batchSize);
        return result;
    }

    /**
     * 更新用户表同时更新数据库和缓存的实现方法
     * @param userInfoRequestDto  UserInfoResponseDto
     * @return
     */
    public boolean updateUserInfo(UserInfoRequestDto userInfoRequestDto){

          if(null ==  userInfoRequestDto){
              return false;
          }

        UserInfo userInfo = UserInfo.build().clone(userInfoRequestDto);

        return userInfoDao.updateById(userInfo);


    }







    /**
     * 通过主键ID删除对象信息实现缓存和数据库,同时删除的方法
     * @param  idList
     * @return
     */
    public int delUserInfoByIds(List<Long> idList){
        boolean result = false;
        if(null == idList){
            return ResultEnum.FAIL.id();
        }
        if( idList.size() == 1) {
            result = userInfoDao.removeById(idList.get(0));
        }else {
            result =  userInfoDao.removeByIds(idList);
        }
        if(result){
            return ResultEnum.SUCCESS.id();
        }
        return ResultEnum.FAIL.id();

    }


    /**
     * 通过主键ID更新对象用户表实现缓存和数据库更新的方法
     * @param  userInfoId
     * @return
     */
    public UserInfoResponseDto getUserInfoById(long userInfoId){
        if(userInfoId < 0 ){
            return null;
        }
        UserInfo userInfo =  userInfoDao.getById(userInfoId);
        if(userInfo == null){
            return null;
        }
        UserInfoResponseDto userInfoResponseDto = UserInfoResponseDto.build().clone(userInfo);

        return userInfoResponseDto ;

    }


    /**
    * 查询条件
    */
    public QueryWrapper<UserInfo> checkQueryCondition(BasePage basePage) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        UserInfoRequestDto userInfoRequestDto = (UserInfoRequestDto) basePage.getParamObject();

                                                                                                                                                                                                                                            return queryWrapper;
    }


    /**
     * 通过分页获取UserInfo信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author xxx
     * @date 2021-05-08 17:45:21
     */
    public List<UserInfoResponseDto> getUserInfoByPage(
            ResponseResultList<UserInfoResponseDto> responseResultList, BasePage basePage){


        List<UserInfoResponseDto> resDtoList = new ArrayList<>();
        if(basePage == null){
            return resDtoList;
        }
        //分页对象        PageHelper
        IPage<UserInfo> iPage = new Page<>(basePage.getPageNo(), basePage.getRealPageSize());
        QueryWrapper<UserInfo> queryWrapper = checkQueryCondition(basePage);

        IPage<UserInfo> page = userInfoDao.page(iPage, queryWrapper);
        if(null == page){
            return resDtoList;
        }

        List<UserInfo>  list = page.getRecords();
        if(null == list || list.isEmpty()){
            return resDtoList;
        }
        list.forEach(userInfo -> {
                UserInfoResponseDto userInfoResponseDto = UserInfoResponseDto.build().clone(userInfo);

            resDtoList.add(userInfoResponseDto);
        });
        responseResultList.setTotal((int) page.getTotal());
        return resDtoList;


    }

    /**
     * 通过分页获取UserInfo信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author xxx
     * @date 2021-05-08 17:45:21
     */
    public ResponseResultList<UserInfoResponseDto> getUserInfoByNextPage(BasePage basePage){
        ResponseResultList<UserInfoResponseDto> responseResultList = ResponseResultList.build();
        List<UserInfoResponseDto>  list = this.getUserInfoByPage(responseResultList,basePage);
        if(null == list ){
            list = new ArrayList<>();
        }
        boolean isNext =  basePage.isNextPage(list);
        responseResultList.toIsNextPage(isNext).toList(list);
        return responseResultList;

    }

    public PageUtils queryPage(Map<String, Object> params) {
        IPage iPage =  new Query<UserInfo>().getPage(params);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        IPage<UserInfo> page = userInfoDao.page(iPage,queryWrapper);
        return new PageUtils(page);
    }


    /**
     * 保存用户表同时更新数据库和缓存的实现方法
     * @return
     */
    public UserInfo  setUserInfo(){
        UserInfo userInfo = new UserInfo();
        /**
 			//userInfo.setCreateDate (Date createDate);
 			//userInfo.setModifyDate (Date modifyDate);
 			//userInfo.setStatus (int status);
 			//userInfo.setHeadImg (String headImg);
 			//userInfo.setUserName (String userName);
 			//userInfo.setLoginName (String loginName);
 			//userInfo.setPassword (String password);
 			//userInfo.setSign (String sign);
 			//userInfo.setMobile (String mobile);
 			//userInfo.setEmail (String email);
 			//userInfo.setRemarks (String remarks);
		**/

        return userInfo;
    }

    public boolean saveData(InputStream initialStream) {
        return ExcelUtils.readExcel(initialStream,userInfoDao, UserInfo.class,0);
    }


    public boolean getByLoginName(String loginName) {
       boolean isExit = userInfoDao.getByLoginName(loginName);
       return isExit;
    }

    /**
     * 用户账号搜索，搜索名称，登陆名称，手机号码
     * @param page 用户账号搜索，搜索名称，登陆名称，手机号码
     * @return List<UserInfo>
     */
    @Override
    public List<UserInfoResponseDto> queryUserPageBySearch(BasePage page ){
      List<UserInfo> list =  userInfoDao.queryUserPageBySearch(page);
      if(null == list || list.isEmpty()){
          return Collections.EMPTY_LIST;
      }
     List<UserInfoResponseDto> responseDtoList =    IterableConverter.convertList(list,UserInfoResponseDto.class);
      return responseDtoList;
    }

    @Override
    public UserInfoResponseDto getUserInfoByLoginName(String loginName) {
        UserInfo userInfo = userInfoDao.getUserInfoByLoginName(loginName);
        if(userInfo == null){
            return null;
        }
        return UserInfoResponseDto.build().clone(userInfo);
    }

    /**
     * 通过主键ID删除对象信息实现缓存和数据库,同时删除的方法
     * @param  idList
     * @return
     */
    public Map<Long,UserInfoResponseDto> getUserInfoByIds(Collection<Long> idList){
        if(CollectionUtils.isEmpty(idList)){
            return null;
        }
        List<UserInfo> users = userInfoDao.getListByIds(idList);
        if(null == users || users.isEmpty()){
            return null;
        }
        Map<Long,UserInfoResponseDto> map = new HashMap<>();
        users.forEach(e->{
            map.put(e.getId(),UserInfoResponseDto.build().clone(e));
        });
        return map;
    }
}
